package com.ff.xyh.serurity.filter;


import com.ff.xyh.common.entity.result.ResultMessage;
import com.ff.xyh.common.utils.ResponseUtil;
import com.ff.xyh.common.entity.result.ResultObject;
import com.ff.xyh.serurity.entity.CurrentUser;
import com.ff.xyh.serurity.entity.LoginInfo;
import com.ff.xyh.serurity.entity.SecurityUser;
import com.ff.xyh.serurity.security.TokenManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * <p>
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        // 配置登录路径 和 请求方法
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher(
                "/access/user/login", "POST"));
    }

    /**
     * 拦截用户登录数据 返回给userDetailsService实现类做认证
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        try {

            /**
             * 相同数据写入 类似于BeanUtils.copyProperties()
             * 比如前端传入 userNickname和 password 则 currentUser
             * 的 userNickname和 password 会被自动填充
             */
            CurrentUser user = new ObjectMapper().readValue(
                    request.getInputStream(), CurrentUser.class);
//            LoginInfo info = new ObjectMapper().readValue(
//                    request.getInputStream(), LoginInfo.class);
            // 返回认证结果
//            System.out.println("CurrentUser ===> " + user);
            return authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(
                            user.getUserToken(), user.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 认证成功
     * 在UserDetailServiceImpl中的loadUserByUsername返回后
     * 经过security框架处理认证成功后调用
     * @param req
     * @param res
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
//        此处放入用户id
        String token = tokenManager.createToken(user.getCurrentUser().getId());
        // 存入String键值对到redis accessUser_userId userToken 在TokenManager会用到 在用户改密码时应该清除

//        redisTemplate.opsForValue().set(
//                "permissionValueList_" + user.getCurrentUser().getId(),
//                user.getPermissionValueList());

        // 存入String键值对到redis permissionValueList_userId permissionValueList
        // 在TokenAuthenticationFilter的UsernamePasswordAuthenticationToken方法中用到
        // 在getUserInfo方法中会写入
//        redisTemplate.opsForValue().set(
//                "permissionValueList_" + user.getCurrentUser().getId(),
//                user.getPermissionValueList()
//        );
//        System.out.println("successfulAuthentication");
        ResponseUtil.out(res, ResultObject.ok().data("token", token));
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, ResultObject.error().message("登录失败"));
    }
}
